import time
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse
from fastapi import Request
from app.dependencies import request_id
from app.config import appLogger


def de(func):
  async def wrapper():
    return func

  return wrapper


async def set_body(request: Request):
  receive_ = await request._receive()

  async def receive():
    return receive_

  request._receive = receive

class LoggingMiddleware(BaseHTTPMiddleware):
  async def dispatch(self, request: Request, call_next):
    # body = None
    # if request.method == "POST" or request.method == "PUT":
    #   if request.headers.get("Content-Type") == "application/json":
    #     body = await request.body()
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    # appLogger.info("request completed", extra={"requestId":request_id.get(), "object":f"[{request.method}]{request.url}", "process_seconds":f"{process_time:.2f}", "query":request.query_params, "body":body})
    appLogger.info("request completed", extra={"requestId":request_id.get(), "object":f"[{request.method}]{request.url}", "process_seconds":f"{process_time:.2f}", "query":request.query_params})
    return response
